package com.example.forum.utils;

import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Optional;
import java.util.Random;

/**
 * 功能描述:
 *
 * @author Lenovo
 * @date 2025/1/17
 */
@Slf4j
@Component
public class MailUtil {
    private final static String SUBJECT = "验证码";

    @Value(value = "${spring.mail.username}")
    private String from;
    @Resource
    private JavaMailSender mailSender;

    /**
     * 发邮件
     *
     * @param to:  目标邮箱地址
     * @param subject： 标题
     * @param context： 正文
     * @return
     */
    public Boolean send(String to, String subject, String context) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(context);
        try {
            mailSender.send(message);
        } catch (Exception e) {
            log.error("向{}发送邮件失败！", to, e);
            return false;
        }
        return true;
    }

    public Integer sendVerificationCode(String toMail) throws Exception {
        StringBuilder text = new StringBuilder();
        Random random = new Random();
        Integer verificationCode = random.nextInt(900000) + 100000;
        text.append("【论坛系统】，您的验证码为：").append(verificationCode).append(",<br/>")
                .append("打死不要告诉别人。");
        send(toMail,SUBJECT,text.toString());
        return verificationCode;
    }
}
